(function($){
    // History
    $.ajaxHistory = new function(){
        var RESET_EVENT = 'historyReset'; 
        var _currentHash = location.hash;       
        var _intervalId = null;
        var _observeHistory; // define outside if/else required by Opera

        this.update = function(){  }; // empty function body for graceful degradation

        // create custom event for state reset
        var _defaultReset = function() {
            $('.remote-output').empty();
        };
        $(document).bind(RESET_EVENT, _defaultReset);
        
        // TODO fix for Safari 3
        // if ($.browser.msie)
        // else if hash != _currentHash
        // else check history length

        /*if ($.browser.msie) 
        {         
            var _historyIframe, initialized = false; // for IE

            // add hidden iframe
            $(function() {
                _historyIframe = $('<iframe style="display: none;"></iframe>').appendTo(document.body).get(0);
                var iframe = _historyIframe.contentWindow.document;
                // create initial history entry
                iframe.open();
                iframe.close();    
                if (_currentHash && _currentHash != '#') {
                    iframe.location.hash = _currentHash.replace('#', '');
                }
            });

            this.update = function(hash) {
                _currentHash = hash;
                var iframe = _historyIframe.contentWindow.document;
                iframe.open();
                iframe.close();
                iframe.location.hash = hash.replace('#', '');
            };

            _observeHistory = function() {
                var iframe = _historyIframe.contentWindow.document;
                var iframeHash = iframe.location.hash;
                if (iframeHash != _currentHash) {
                    _currentHash = iframeHash;   
                    if (iframeHash && iframeHash != '#') {
                        // order does matter, set location.hash after triggering the click...
                        //$('a[@href$="' + iframeHash + '"]').click();
                        $.ajaxHistory.ajax(iframeHash);
                        location.hash = iframeHash;
                    } else if (initialized) {
                        $.ajaxHistory.ajax();
                        location.hash = '';
                        $(document).trigger(RESET_EVENT);
                    }
                }
                initialized = true;
            };

        } 
        else */
        if ($.browser.mozilla || $.browser.opera || $.browser.msie || $.browser.webkit) 
        {   
            this.update = function(hash) {
                _currentHash = hash;
            };
                  
            _observeHistory = function() 
            {         
                if(location.hash) {     
                    if (_currentHash != location.hash) {   //alert('new click');   
                        _currentHash = location.hash; 
                        //$('a[@href$="' + _currentHash + '"]').click();
                        $.ajaxHistory.ajax(_currentHash);
                    }      
                } 
                else if(_currentHash)    
                {             
                    $.ajaxHistory.ajax();
                    _currentHash = '';
                    $(document).trigger(RESET_EVENT);  
                }    
            };
                        
        } 
        else if ($.browser.safari) 
        {        
            var _backStack, _forwardStack, _addHistory; // for Safari

            // etablish back/forward stacks
            $(function() {
                _backStack = [];
                _backStack.length = history.length;
                _forwardStack = [];

            });
            var isFirst = false, initialized = false;
            _addHistory = function(hash) {
                _backStack.push(hash);
                _forwardStack.length = 0; // clear forwardStack (true click occured)
                isFirst = false;
            };

            this.update = function(hash) {
                _currentHash = hash;
                _addHistory(_currentHash);
            };

            _observeHistory = function() {    
                var historyDelta = history.length - _backStack.length;
                if (historyDelta) { // back or forward button has been pushed
                    isFirst = false;
                    if (historyDelta < 0) { // back button has been pushed
                        // move items to forward stack
                        for (var i = 0; i < Math.abs(historyDelta); i++) _forwardStack.unshift(_backStack.pop());
                    } else { // forward button has been pushed
                        // move items to back stack
                        for (var i = 0; i < historyDelta; i++) _backStack.push(_forwardStack.shift());
                    }
                    var cachedHash = _backStack[_backStack.length - 1];
                    //$('a[@href$="' + cachedHash + '"]').click();
                    $.ajaxHistory.ajax(cachedHash);    
                    _currentHash = location.hash;
                } else if (_backStack[_backStack.length - 1] == undefined && !isFirst) {
                    // back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
                    // document.URL doesn't change in Safari
                    if (document.URL.indexOf('#') >= 0) {
                        $.ajaxHistory.ajax('#' + document.URL.split('#')[1]);
                        //$('a[@href$="' + '#' + document.URL.split('#')[1] + '"]').click();
                    } else if (initialized) {
                        $.ajaxHistory.ajax();
                        $(document).trigger(RESET_EVENT);
                    }
                    isFirst = true;
                }
                initialized = true;
            };

        } 
        
        this.initialize = function(callback) 
        {                      
            // custom callback to reset app state (no hash in url)
            if (typeof callback == 'function') {     
                $(document).unbind(RESET_EVENT, _defaultReset).bind(RESET_EVENT, callback);
            }           
            // look for hash in current URL (not Safari)
            if (location.hash && typeof _addHistory == 'undefined') {   
                //$('a[@href$="' + location.hash + '"]').trigger('click');
                //$.ajaxHistory.ajax();
            }          
            // start observer
            if (_observeHistory && _intervalId == null) {
                _intervalId = setInterval(_observeHistory, 200); // Safari needs at least 200 ms
            }
        };
        
        this.checkLoginForum = function(username)
        {	
        	$.ajax({
      	      url: 'http://192.168.4.108/sohagame/?fnc=check_login_forum',
      	      type: 'GET',
      		  data: {
      				'username':username      															
      		  },			      
      	      dataType: 'html',
      		  timeout: 10000,				  
      	      success: function(data){
      			  //alert (data);
      	      }
        	});
            return false;
        };
        
        this.ajax = function(href, data)    
        {       
            if(typeof href == 'undefined'){
                href = '#fnc=game_display'; 
            }     
            href = href.replace('#', '?'); 
            if(typeof data == 'undefined') data = '';    
                    
            $.ajax({
                url: 'http://192.168.4.108/sohagame/'+ href, 
                cache: false, 
                data: data,
                dataType: 'jsonp', 
                contentType: "application/json; charset=utf-8", 
                beforeSend: function() { if(typeof data.error != 'undefined') $("div#jq_update").html("<center> <img border=\"0\" src=\"http://192.168.4.108/sohagame/webskins/images/ajax-loader.gif\" /> </center> <br />"); }, 
                /*timeout: 5000,*/ 
                error: function(request, error){ alert(error); },  
                success: function(data){ if(data.error){ alert(data.error); if(data.back) history.go(-1); } else if (data.redirect) window.location.href = data.redirect; else $('div#jq_update').html(data.html); }
            }); 
            return false;  
        };
        
        
    };
    
    // Update
    $.fn.update = function(output){ if(location.hash=='') return $.ajaxHistory.ajax(); else return $.ajaxHistory.ajax(location.hash); } 
})(jQuery);